import React, { useMemo } from "react";
import { View, Image } from "@tarojs/components";
import Item from "./components/Item";
import emptyPng from "./imgs/empty.png";

import "./index.less";

const GAP = 32;
const AD_HEIGHT = 300;
const ITEM_HEIGHT = 480;

const List = ({ dataSource, onItemClick }) => {
  const listData = useMemo(() => {
    const left = [];
    const right = [];
    let leftHeight = 0;
    let rightHeight = 0;
    dataSource.forEach((item) => {
      const itemHeight = item.type === "ad" ? AD_HEIGHT : ITEM_HEIGHT;
      if (rightHeight - leftHeight >= 0) {
        left.push(item);
        leftHeight += itemHeight;
        leftHeight += GAP;
      } else {
        right.push(item);
        rightHeight += itemHeight;
        rightHeight += GAP;
      }
    });
    return {
      left,
      right,
      empty: !left.length && !right.length,
    };
  }, [dataSource]);

  return (
    <View class="list">
      {listData.empty ? (
        <View className="list-empty">
          <Image className="img-empty" src={emptyPng}></Image>
        </View>
      ) : (
        <>
          <View class="list-left">
            {listData.left.map((item) => {
              return (
                <Item
                  key={item.id}
                  data={item}
                  onClick={(data) => {
                    onItemClick && onItemClick(data);
                  }}
                ></Item>
              );
            })}
          </View>
          <View class="list-right">
            {listData.right.map((item) => {
              return (
                <Item
                  key={item.id}
                  data={item}
                  onClick={(data) => {
                    onItemClick && onItemClick(data);
                  }}
                ></Item>
              );
            })}
          </View>
        </>
      )}
    </View>
  );
};

export default List;
